package cn.edu.zafu.bigdata.bd121.except;

/**
 * 下标越界异常捕获demo
 *
 * @author 202211090121
 */
public class IndexOutOfBoundsExample {

    /**
     * 获取数组元素
     *
     * @param arr   数组
     * @param index 下标
     * @return 数组元素
     * @throws ArrayIndexOutOfBoundsException 下标越界异常
     */
    public static int getElement(int[] arr, int index) {
        if (arr == null) {
            throw new IllegalArgumentException("数组不能为空");
        }
        if (index < 0 || index >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("下标 " + index + " 超出数组范围");
        }
        return arr[index];
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        try {
            // 尝试下标越界，将抛出异常
            int element = getElement(arr, -1);
            System.err.println("元素是: " + element);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知错误: " + e.getMessage());
        }
    }
}
